<template>
    <div class="signeList">
        <Row>
            <Col :xs="24">
                <div class="margin-up-down">
                    <Select v-model="info.crOrgCode" clearable style="width:155px" placeholder="请选择建档机构" >
                        <Option v-for="item in hospitalList" :value="item.orgCode" :key="item.orgCode" style='text-align:center'>{{ item.orgName }}</Option>
                    </Select> 
                </div>
                <div class="margin-up-down">
                    <Select v-model="info.liveProvinceCode" clearable style="width:155px" placeholder="省" @on-change="getCity">
                        <Option v-for="item in provinceList" :value="item.code" :key="item.id" style='text-align:center'>{{ item.name }}</Option>
                    </Select> 
                </div>
                <div class="margin-up-down">
                    <Select v-model="info.liveCityCode" clearable style="width:155px" placeholder="市" @on-change="getArea">
                        <Option v-for="item in cityList" :value="item.code" :key="item.id" style='text-align:center'>{{ item.city }}</Option>
                    </Select> 
                </div>
                <div class="margin-up-down">
                    <Select v-model="info.liveDistrictCode" clearable style="width:155px" placeholder="县/区" @on-change="getStreets">
                        <Option v-for="item in areaList" :value="item.code" :key="item.id" style='text-align:center'>{{ item.area }}</Option>
                    </Select> 
                </div>
                <div class="margin-up-down">
                    <Select v-model="info.liveStreetCode" clearable style="width:155px" placeholder="乡镇" @on-change="getVillages">
                        <Option v-for="item in streetsList" :value="item.code" :key="item.id" style='text-align:center'>{{ item.name }}</Option>
                    </Select> 
                </div>
                <div class="margin-up-down">
                    <Select v-model="info.liveCountryCode" clearable style="width:155px" placeholder="村（小区）" >
                        <Option v-for="item in villagesList" :value="item.code" :key="item.id" style='text-align:center'>{{ item.name }}</Option>
                    </Select> 
                </div>
                <div class="margin-up-down">
                    <Input class="w-input" v-model="info.name" placeholder="请输入患者姓名"/>                                            
                </div>
                <div class="margin-up-down">
                    <Input class="w-input" v-model="info.idNo" placeholder="请输入身份证号"/>                                            
                </div>
                <div class="margin-up-down">
                    <Button type="primary" @click="loadPage(1)" class="btn">
                        <Icon type="ios-search" size="14"/>
                    </Button>
                </div>
                <div class="margin-up-down">
                    <Button icon="icon-gengxin" @click="reset" class="btn">
                        <i class = "iconfont icon-gengxin" style="font-size:16px;margin-left:-8px;"></i>
                    </Button>
                </div>
            </Col>
        </Row>
        <div>
            <Button type="primary" @click="handleSelectAll(!falg,0)" class="btnL">全选当前页</Button>
            <Button type="primary" @click="handleSelectAll(!falg,1)" class="btnL">全选所有页</Button>
            <Button type="info" @click="moveInto" class="btnR">
                批量迁入
            </Button>
            <div style="clear: both;"></div>
        </div> 
        <Table class="m-table" stripe :columns="columns" :data="unsignList" ref= 'selection' @on-selection-change='handleSelectChange'>
            <!-- //原生写法 -->
            <!-- ref= 'table' -->
            <!-- <template slot="flag" slot-scope="props" >
                <Checkbox v-model="props.row.flag" @on-change="handleRowChange(props.row)"></Checkbox>                            
            </template> -->
        </Table>
        <div class="page">
            <Page :total="count" :current='info.pageNo' :page-size="info.pageSize" show-total show-elevator @on-change="loadPage"/>
        </div>
        <div style="text-align: center;">
            <Button @click="ok">
                <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>返回
            </Button>
        </div>
        <!-- 电子健康档案批量迁入 -->
        <Modal
            v-model="ModalStatus"
            title = '电子健康档案批量迁入'
            width="800"
            :mask-closable="false"
            footer-hide
        >
            <div class = 'signe'>
                <p class="number">您已选择 <span class="tishi">（{{signNum}} 份）</span>电子健康档案，请选择需要迁入的家庭医生团队。</p>
                <div class="team">
                    <div class="teaminfo">
                        <div>
                            <span style="font-size: 14px;font-weight: 550;"><i style="color:red;margin-right:5px">*</i>服务机构:</span>
                            <Select v-model="service.hospitalId" clearable style="width:155px" placeholder="请选择服务机构" @on-change='loadDoctorGroup'>
                                <Option v-for="item in hospitalList" :value="item.id" :key="item.id" style='text-align:center'>{{ item.orgName }}</Option>
                            </Select> 
                        </div>
                        <p>团队负责人姓名：{{captain}}</p>
                        <p>负责护士姓名：
                            <span v-for="item in nurse"  :key="item.id" style="margin-right:15px">{{item.doctorName}}</span> 
                        </p>
                        <p>负责村医：
                            <span  v-for="item in villageDoctor"  :key="item.id" style="margin-right:15px">{{item.doctorName}}</span> 
                        </p>
                    </div>
                    <div class="teaminfo">
                        <div>
                            <span style="font-size: 14px;font-weight: 550;"><i style="color:red;margin-right:5px">*</i>服务团队:</span>
                            <Select v-model="service.teamId" clearable style="width:155px" placeholder="请选择服务团队" @on-change='doctorGroupInfo'>
                                <Option v-for="item in doctorGroupList" :value="item.id" :key="item.id" style='text-align:center'>{{ item.name }}</Option>
                            </Select> 
                        </div>
                        <p>全科医生姓名：
                            <span v-for="item in doctorName"  :key="item.id" style="margin-right:15px">{{item.doctorName}}</span> 
                        </p>
                        <p>签约团队联系电话：{{telephone}}</p>
                        <p>联系电话：{{phone}}</p>
                    </div>
                </div>
            </div>
            <div style='margin-top:10px;width:200px;margin:10px auto;'>
                <Button type="primary" @click="submit" :disabled='disabledSave' class="btn">
                    <Icon type="ios-checkmark" style="margin-right: 5px" />提交
                </Button>
                <Button style="marginLeft: 20px" @click="back" class="btn">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
                </Button>
            </div>
        </Modal>
        <Modal
            v-model="ModalStatus2"
            title = '电子健康档案批量迁入-结果提示'
            width="600"
            :mask-closable="false"
            footer-hide
        >
            <div class = 'signe'>
                <p class="number">您已选择 <span class="tishi">（{{allBaseNum}} 份）</span>电子健康档案，成功迁入<span class="tishi">（{{moveInNum}} 份）</span>，失败<span class="tishi">（{{failNum}} 份）</span>。</p>
            </div>
            <div style='margin-top:10px;width:200px;margin:10px auto;'>
                <Button type="primary" @click="ok" class="btn">
                    <Icon type="ios-checkmark" style="margin-right: 5px" />确定
                </Button>
                <Button style="marginLeft: 20px" @click="goback" class="btn">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>关闭
                </Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import api from "@/api/commonApi";
import newfourLevelLinkage from "@/components/newfourLevelLinkage";
import Utils from "@/utils";
import {encrypt,decrypt} from "@/plugins/qwAes.js";
export default { 
    components: {
        newfourLevelLinkage,
    },
    data() {
        return {
            province: null,
            city: null,
            area: null,
            hospitalList: [],
            doctorGroupList: [],
            info: {
                // hospitalId: null,
                crOrgCode: null,
                liveProvinceCode: null,
                liveCityCode: null,
                liveDistrictCode: null,
                liveStreetCode: null,
                // streetsId: null,
                // villagesId: null,
                liveCountryCode: null,
                name: '',
                idNo: '',
                moveInStatus: 2,           //1:已迁入数据 2:未迁入数据
                pageNo: 1,          
                pageSize: 10,          
            },
            searchKey: "",
            time: [],
            flag: false,
            currentChoose: [],
            columns: [
                {
                    type: 'selection',       //组件写法
                    title: "选择",
                    key: "id",
                    width: 70,
                    align: "center",
                    //原生写法
                    // render: (h, params) => {
                    //     this.unsignList[params.index] = params.row
                    //     return h("div", 
                    //         this.$refs.table.$scopedSlots.flag({
                    //                 row: params.row,
                    //                 idx: params.row._index
                    //             }) 
                    //     );
                    // }

                   
                },
                {
                    title: "排序",
                    key: "sum",
                    width: 60,
                    align: "center",
                    render: (h, params) => {
                        let sum = (this.info.pageNo - 1) * this.info.pageSize + params.index + 1;
                        return h("span", sum);
                    },
                },
                {
                    title: "姓名",
                    key: "name",
                    align: "center",
                    width: 150,
                },
                {
                    title: "身份证号",
                    key: "idNo",
                    align: "center",
                    render: (h, params) => {
                        if (params.row.idNo) {
                            // let idcard = String(params.row.idcard).replace(/(\d{6})\d{8}(\d{4})/g,'$1********$2');
                            // return idcard
                            var str1 = params.row.idNo.slice(0, 6);
                            var str2 = "";
                            var str3 = params.row.idNo.slice(14);
                            if (params.row.idNo.length == 15) {
                                str2 = "*****";
                            } else {
                                str2 = "********";
                            }
                            let idNo = str1 + str2 + str3;
                            return idNo;
                        }
                    },
                },
                { title: "家庭地址", key: "address", align: "center",
                    render: (h, params) => {
                        let row = params.row;
                        let address = row.liveProvince + row.liveCity + row.liveDistrict + row.liveStreet + row.liveCountry;
                        return h("span", address);
                    },
                },
                { title: "建档机构", key: "crOrgName", align: "center" },
                {
                    title: "建档时间",
                    key: "crDate",
                    align: "center",
                    width: 150,
                },
                {
                    title: "设置",
                    key: "iOperate",
                    width: 160,
                    align: "center",
                    render: (h, params) => {
                        let row = params.row;
                        return h("div", [
                            h(
                                "span",
                                {
                                    props: {
                                        size: "small",
                                    },
                                    style: {
                                        color: "#5362e1",
                                        margin: "0px 6px",
                                    },
                                    on: {
                                        click: () => {
                                            // window.open('http://3sy2830370.imdo.co/qw/browser.html?Authorization=' + encrypt('idNo='+ row.idNo)+'&invoker=1#/overview');
                                            
                                            window.open('http://3sy2830370.imdo.co/qw/browser.html?Authorization=' + encrypt('idNo=340323201709163756')+'&invoker=1#/overview');
                                        },
                                    },
                                },
                                "EHR"
                            ),
                            "|",
                            h(
                                "span",
                                {
                                    props: {
                                        type: "error",
                                        size: "small",
                                    },
                                    style: {
                                        color: "#fc6c49",
                                        marginLeft: "6px",
                                    },
                                    on: {
                                        click: () => {
                                            // this.handleRemove(row);
                                        },
                                    },
                                },
                                "EMR"
                            )
                        ]);
                    },
                },
            ],
            unsignList: [],
            provinceList: [],
            cityList: [],
            areaList: [],
            streetsList: [],
            villagesList: [],
            count: 0,
            pageSize: 10,
            pageNo: 1,
            disabledSave: false,
            ModalStatus: false,
            ModalStatus2: false,  
            service: {
                hospitalId: null,
                teamId: null,
                baseIdList: []
            },
            checkList: [],
            signNum: 0,
            allBaseNum: '',      //选择档案数
            moveInNum: '',        //迁入成功数
            failNum: '',        //迁入失败数
            captain: '',       //队长
            nurse: [],       //护士
            villageDoctor: [],       //村医
            doctorName: [],       //全科医生
            telephone: '',       //签约团队联系电话
            phone: '',       //联系电话
            pageStatus: '',       //联系电话
            personList: [],
        };
    },
    created() {
        // console.log(decrypt('1Nl+Abzbv6lehNYyzDd0H3R3GwsSKg8Lh8KUqwr7YdA=')) 
        this.hospital = this.$route.query.hospital
            ? this.$route.query.hospital
            : null;
        let breadList = [
            { path: "/index", title: "首页" },
            {
                path: "/index/operation/ordersmanagement/index",
                title: "订单管理"
            },
            {
                path: "/index/comprehensive/registration/list",
                title: "预约挂号订单"
            }
        ];
        this.$emit("changeBreadList", breadList);
    },
    mounted() {
        let pageNo = this.$route.query.pageNo;
        pageNo = pageNo ? pageNo : 1;
        //上来就加载第一页数据
        this.loadPage(1);
        this.getHospital()
        this.getProvince()
    },
    methods: {
        //原生写法
        handleRowChange(val){
            if(val.flag ==true){
                this.currentChoose.push(val);
            }
            if(val.flag ==false) {
                this.currentChoose.forEach((i, index) =>{
                    if(i.id == val.id){
                        this.currentChoose.splice(index,1)
                    }
                })
            }
            // console.log('选中的数据',this.currentChoose)
        },                  
        getProvince() {
            this.$axios.post(api.findProvinceList,{}).then(resp => {
                if (resp.data.success) {
                    let ret = resp.data.object;
                    //    console.log('省级',ret)
                    if(ret){
                        this.provinceList = ret;
                    } else {
                        this.provinceList = [];
                    }                      
                } else {
                    this.provinceList = [];
                }
            })
            .catch(err => {
                console.log(err);
            });
        },
        getCity() {
            this.info.liveCityCode = ''
            this.info.liveDistrictCode = ''
            this.info.liveStreetCode = ''
            this.info.liveCountryCode = ''
            this.cityList = []
            this.areaList = []
            this.streetsList = []
            this.villagesList = []
            if(this.info.liveProvinceCode) {
                this.$axios.post(api.findCity, {code: this.info.liveProvinceCode}).then(resp => {
                    if (resp.data.success) {
                        let ret = resp.data.object;
                        //    console.log('市级',ret)
                        if(ret){
                            this.cityList = ret;
                        } else {
                            this.cityList = [];
                        }                      
                    } else {
                        this.cityList = [];
                    }
                })
                .catch(err => {
                    console.log(err);
                });
            }
        },
        getArea() {
            this.info.liveDistrictCode = ''
            this.info.liveStreetCode = ''
            this.info.liveCountryCode = ''
            this.areaList = []
            this.streetsList = []
            this.villagesList = []
            if(this.info.liveCityCode) {
                this.$axios.post(api.getCounty, {cityCode: this.info.liveCityCode}).then(resp => {
                    if (resp.data.success) {
                        let ret = resp.data.object;
                        //    console.log('区县级',ret)
                        if(ret){
                            this.areaList = ret;
                        } else {
                            this.areaList = [];
                        }                      
                    } else {
                        this.areaList = [];
                    }
                })
                .catch(err => {
                    console.log(err);
                });
            }
        },
        //乡镇阶段 第4级
        getStreets() {
            this.info.liveStreetCode = ''
            this.info.liveCountryCode = ''
            this.streetsList = []
            this.villagesList = []
            if(this.info.liveDistrictCode) {
                this.$axios.post(api.streetsList, {areaCode: this.info.liveDistrictCode}).then(resp => {
                    if (resp.data.success) {
                        let ret = resp.data.object;
                        // console.log('乡镇阶段 第4级',ret)
                        if(ret){
                            this.streetsList = ret;
                        } else {
                            this.streetsList = [];
                        }                      
                    } else {
                        this.streetsList = [];
                    }
                })
                .catch(err => {
                    console.log(err);
                });
            }
        },
        //社区村接口 第5级
        getVillages() {
            this.info.liveCountryCode = ''
            this.villagesList = []
            if(this.info.liveStreetCode) {
                this.$axios.post(api.villagesList, {streetsCode: this.info.liveStreetCode}).then(resp => {
                    if (resp.data.success) {
                        let ret = resp.data.object;
                        //    console.log('社区村接口 第5级',ret)
                        if(ret){
                            this.villagesList = ret;
                        } else {
                            this.villagesList = [];
                        }                      
                    } else {
                        this.villagesList = [];
                    }
                })
                .catch(err => {
                    console.log(err);
                });
            } 
        },
        handleSelectChange(currentRow, oldCurrentRow) {
            if(this.pageStatus == 1) {
                this.pageStatus = ''
            }
            if(currentRow.length) {
                this.currentChoose = currentRow
                
            } else {
                this.currentChoose = []
                this.unsignList.forEach(c =>{
                    c["_checked"] = false;
                })
            }   
        },
        handleSelectAll (status,val) {
            if(val == 0) {
                this.currentChoose = []
                this.pageStatus = 0               //全选当前页
                this.$refs.selection.selectAll(status);
                this.currentChoose = this.$refs.selection.data
                this.signNum = this.currentChoose.length
            } else if(val == 1) {
                this.pageStatus = 1              //全选所有页
                this.loadPage(1)
                this.signNum = this.count 
            }  
        },
        //获取医疗机构
        getHospital() {
            let body = {
                pageNo: 1,
                pageSize: 1000,
                hospitalType: 1,
                haveFdsTeam: 1,
            };
            this.$axios.post(api.mechanismregList, body).then(res => {
                if (res.data.code) {
                    let ret = res.data.object;
                    if(ret.records){
                        this.hospitalList = ret.records;
                        // console.log(this.hospitalList)
                    } else {
                        this.hospitalList = []
                    }
                } 
            }).catch(() => {

            });
        },
        //医生小组管理-分页列表
        loadDoctorGroup() {
            this.service.teamId = ''
            this.captain = ''
            this.telephone = ''
            this.phone = ''
            var params = {};
            params.hospitalId= this.service.hospitalId ? this.service.hospitalId : null;
            params.pageNo = 1;
            params.pageSize = 1000;  
            params.type = 1;  
            this.$axios.post(api.findTeamDtoList,params).then(res => {
                if(res.data.success) {
                    let ret = res.data.object
                    if(ret.records) {
                        this.doctorGroupList = ret.records
                    } else {
                        this.doctorGroupList = []
                    }                  
                }   
            })
        },
        //获取家医团队小组信息
        doctorGroupInfo() {
            this.nurse = []
            this.villageDoctor = []
            this.doctorName = []
            if(this.service.teamId) {
                this.$axios.post(api.findTeamById, {
                    id: this.service.teamId
                }).then(res => {
                    if(res.data.success) {
                        let ret = res.data.object;
                        this.captain = ret.doctorName
                        this.telephone = ret.phone
                        if(ret.list) {
                            this.personList = ret.list
                            ret.list.forEach((item,index) => {
                                if(item.role == 2) {
                                    this.doctorName.push(item)
                                } else if(item.role == 3) {
                                    this.nurse.push(item)
                                } else if(item.role == 4) {
                                    this.villageDoctor.push(item)
                                } else if(item.role == 1) {
                                    this.phone = item.phone
                                }
                            })
                        }
                    }
                }).catch(err => {
                    this.$Message.error("加载团队信息失败")
                })
            } else {
                return
            }
        },
        //加载列表数据
        loadPage(pageNo) {
            this.info.pageNo = pageNo;
            this.$axios.post(api.pbasePage, this.info).then(resp => {
                if (resp.data.success) {
                    let ret = resp.data.object;
                    this.count = ret.total
                    if(ret.records){
                        ret.records.forEach((item,index) => {
                            if(this.currentChoose) {
                                this.currentChoose.forEach(c =>{
                                    if(item.id == c.id){
                                        // item.flag = true;
                                        item["_checked"] = true;
                                    }
                                })
                            } 
                            if(this.pageStatus == 1){
                                item.flag = true;
                                item["_checked"] = true;  
                                this.currentChoose = ret.records   //直接点击全选所有页按钮，解决点击批量迁入提示无数据问题，不可删 
                            }
                        }) 
                        this.unsignList = ret.records;  
                    } else {
                        this.unsignList = [];
                    }                      
                } else {
                    this.unsignList = [];
                }
            })
            .catch(err => {
                this.unsignList = [];
                console.log(err);
            });
        },
        //迁入
        moveInto() {
            //控制全选在取消全选，点击批量迁入无效
            if(!this.currentChoose.length) {
                this.$Message.error("请选择要迁入的数据")
                return  
            }
            if((this.pageStatus == 0 || this.pageStatus == '') && !this.currentChoose.length) {
                this.$Message.error("请选择要迁入的数据")
                return  
            } else {
                this.ModalStatus = true
                if(this.pageStatus == 1) {
                    this.signNum = this.count
                } else {
                    this.signNum = this.currentChoose.length
                }
                this.loadDoctorGroup() 
            }
        },
        //确定迁入档案
        submit() {
            this.disabledSave = true 
            if(!this.service.hospitalId) {
                this.$Message.error("请选择服务机构")
                this.disabledSave = false
                return
            }
            if(!this.service.teamId) {
                this.$Message.error("请选择服务团队")
                this.disabledSave = false
                return
            }
            if(this.pageStatus == 0 || this.pageStatus == '') {
                //    this.checkList.forEach
                this.currentChoose.forEach( i =>{
                    this.service.baseIdList.push(i.id) 
                })
            } else if(this.pageStatus == 1) {
                this.service.allPage = 1
            }
            this.$axios.post(api.pbaseMoveIn, this.service).then(resp => {
                if (resp.data.success) {
                    let ret = resp.data.object;
                    this.allBaseNum = ret.allBaseNum
                    this.moveInNum = ret.moveInNum
                    this.failNum = ret.failNum
                    this.disabledSave = false  
                    this.back()
                    this.ModalStatus2 = true                          
                } else {
                    this.disabledSave = false
                    this.$Message.error(resp.data.object.message)
                }
            })
            .catch(err => {
                this.disabledSave = false
                this.$Message.error("resp.data.object.message")
            });
        },
        back() {
            this.disabledSave = false 
            this.ModalStatus = false
            this.service.hospitalId = null
            this.service.teamId = null
            this.signNum = ''
            this.captain = ''
            this.nurse = []
            this.villageDoctor = []
            this.doctorName = []
            this.telephone = ''
            this.phone = ''
        },
        ok() {
            this.ModalStatus = false
            this.ModalStatus2 = false
            this.functionJS.queryNavgationTo(
                this,
                '/index/publicOperation/healthDocument/signeList',
            );
        },
        goback() {
            this.ModalStatus2 = false
            this.loadPage(1);
            // location.reload();
        },
        //清除
        reset() {
            this.info = {}
            this.cityList = []
            this.areaList = []
            this.streetsList = []
            this.villagesList = []
            this.currentChoose = []
            this.pageStatus = ''
            this.info.moveInStatus = 2
            this.info.pageSize = 10
            this.loadPage(1);
        },
    }
};
</script>
<style lang="less" scoped>
.signeList {
    padding: 10px;
    width: 100%;
    background: #ffffff;
    box-sizing: border-box;
    min-height: 600px;
    .w-select {
        width: 100px;
    }
    .w-input {
        width: 220px;
    }
    .m-table {
        margin: 10px 0;
    }
    .margin-up-down {
        display: inline-block;
        margin: 10px 0;
    }
    .btn {
        width: 50px;
        height: 32px;
        line-height: 18px;
    }
    .btnL {
        float: left;
        margin-right: 10px;
    }
    .btnR {
        float: right;
    }
    .page {
        width: 100%;
        margin: 10px auto;
        text-align: center;
    }
    .num {
        padding: 10px 0;
        span {
            margin-right: 80px;
        }
    }
}
.signe {
    width:90%;
    height:auto;
    display:flex;
    margin:0 auto;
    flex-direction:column;
    h2{
        font-weight:bold;
    }
}
.number {
    font-size: 14px;
    font-weight: 550;
    text-align: center;
}
.tishi {
    color: #5362e1;
}
.team {
    display: flex;
    margin: 20px 0;
    .teaminfo {
        width: 50%;
        p {
            font-size: 14px;
            margin: 10px 0;
        }
    }
}
</style>